// 获取用户列表云函数
"use strict";

const db = uniCloud.database();
const usersCollection = db.collection("users");

exports.main = async (event, context) => {
  try {
    // 获取查询参数
    const {
      page = 1,
      pageSize = 10,
      keyword = "",
      role = "",
      status = "",
      type = "",
    } = event;

    // 构建查询条件
    const condition = {
      user_type: "admin", // 默认查询管理员用户
    };

    // 如果传入了type参数，则按照type进行查询
    if (type && type !== "admin") {
      // 查询C端用户
      condition.user_type = type;
    }

    // 关键词搜索
    if (keyword) {
      condition.$or = [
        { username: new RegExp(keyword, "i") },
        { nickname: new RegExp(keyword, "i") },
      ];
    }

    // 按角色筛选（仅对管理员用户有效）
    if (role && condition.user_type === "admin") {
      condition.role = role;
    }

    // 按状态筛选
    if (status !== "") {
      condition.status = parseInt(status);
    }

    // 查询总数
    const countResult = await usersCollection.where(condition).count();
    const total = countResult.total;

    // 查询分页数据
    const result = await usersCollection
      .where(condition)
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .orderBy("register_date", "desc")
      .get();

    return {
      code: 0,
      message: "获取用户列表成功",
      data: {
        list: result.data,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    };
  } catch (error) {
    console.error("获取用户列表失败:", error);
    return {
      code: -1,
      message: "获取用户列表失败: " + error.message,
    };
  }
};
